package com.ruge.tool.sign;

import com.ruge.tool.digest.DigestTool;
import com.ruge.tool.id.IdTool;
import com.ruge.tool.map.MapTool;
import com.ruge.tool.str.StringTool;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author ruge.wu
 * @version 2022-01-06 23:04
 **/
@Slf4j
public class SignTool {
    /**
     * 签名构建
     *
     * @param envUrl    环境url
     * @param serverUrl 服务url
     * @param appKey    appKey
     * @param secretKey 验签key
     * @return 签名
     */
    public static String buildTimaUrl(String envUrl, String serverUrl, String appKey, String secretKey) throws UnsupportedEncodingException {
        envUrl = StringTool.mustEndWith(envUrl, "/");
        serverUrl = StringTool.mustNotStartWith(serverUrl, "/");
        serverUrl = StringTool.contains(serverUrl, "?") ? serverUrl : serverUrl + "?";
        Map<String, String> urlParams = MapTool.getUrlParams(serverUrl);
        urlParams.put("appkey", appKey);
        urlParams.remove("sign");
        urlParams.put("nonce", IdTool.fastUUID());
        urlParams.put("signt", System.currentTimeMillis() + "");
        urlParams = MapTool.sortByKey(urlParams);
        System.out.println(urlParams);
        String buildUrlParams = MapTool.buildUrlParams(urlParams);
        buildUrlParams = StringTool.concat(serverUrl.substring(0, serverUrl.indexOf('?')), '_', buildUrlParams.replaceAll("&", "_"), '_', secretKey);
        assert buildUrlParams != null;
        System.out.println("encode1=="+buildUrlParams);
        String encode = URLEncoder.encode(buildUrlParams, "UTF-8");
        System.out.println("encode2=="+encode);
        String sign = DigestTool.md5Hex(encode);
        urlParams.put("sign", sign);
        System.out.println(sign);
        String result = StringTool.concat(envUrl, serverUrl.substring(0, serverUrl.indexOf("?")), "?", MapTool.buildUrlParams(urlParams));
        return result;
    }
}
